from pydantic import BaseModel, EmailStr, field_validator
import re
from datetime import datetime


class UserOut(BaseModel):
    id: int
    username: str
    email: str
    crawl_count: int
    groups_id: int


class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    is_active: bool
    created_at: datetime

    # 验证用户名
    @field_validator("username")
    def username_validate(cls, value):
        assert 2 <= len(value) <= 32, '用户名长度必须在3到32个字符之间'
        return value

    # 验证密码
    @field_validator("password")
    def password_validate(cls, value):
        assert len(value) >= 8, '密码长度必须至少为8个字符'
        assert re.search("[A-Z]", value), '密码必须包含至少一个大写字母'
        assert re.search("[a-z]", value), '密码必须包含至少一个小写字母'
        assert re.search("[0-9]", value), '密码必须包含至少一个数字'
        assert re.search("[^a-zA-Z0-9]", value), '密码必须包含至少一个特殊字符（如!@#$%^&*等）'
        return value

    # 验证邮箱格式
    @field_validator("email")
    def email_validate(cls, value):
        assert re.match(r"[^@]+@[^@]+\.[^@]+", value), '无效的邮箱格式'
        return value
